package com.tensquareuser.user.controller;

import com.tensquareuser.user.pojo.User;
import com.tensquareuser.user.service.UserService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 后端内部  自己用的方法         供friend模块远程调用
     * 更新 好友粉丝数 和 用户关注数
     * @param x
     * @param userid
     * @param friendid
     */
    @RequestMapping(value="/{x}/{userid}/{friendid}",method = RequestMethod.PUT)
    public void addfanscountandfollowcount(@PathVariable int x,@PathVariable String userid,@PathVariable String friendid){
        userService.addfanscountandfollowcount(x,userid,friendid);
    }

    //登录 用 手机号和密码
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
        User userLogin = userService.login(user.getMobile(),user.getPassword());
        if(userLogin==null){
            return new Result(true, StatusCode.OK, "登录失败");
        }
        //使得后端可以通话的操作，采用jwt来实现
        String token = jwtUtil.createJWT(userLogin.getId(), userLogin.getMobile(), "user");
        Map map = new HashMap();
        map.put("token",token);
        map.put("roles","user");
        return new Result(true, StatusCode.OK, "登录成功",map);
    }

//    {
//         "flag": true,
//         "code": 20000,
//         "message": "登录成功",
//         "data": {
//         "roles": "user",
//         "token": "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjA0NjU4NzEzNzQ3NjU2NzA0Iiwic3ViIjoiMTU3MzY5MzY0MDciLCJpYXQiOjE1NzYwNTE5NzEsInJvbGVzIjoidXNlciIsImV4cCI6MTU3NjA1NTU3MX0.eniQvAmrwsDRmOwBST9MopOR8wagGtt9Mk6Yt-Lr46g"
//    }
//    }


    @RequestMapping(value="/sendsms/{mobile}",method = RequestMethod.GET)
				public Result sendSms(@PathVariable String mobile){
								userService.sendSms(mobile);//随机数 业务层整
					return new Result(true,StatusCode.OK,"发送成功");
				}


    //注册  --验证
    @RequestMapping(value ="/register/{code}",method=RequestMethod.POST)
    public Result regist(@PathVariable String code,@RequestBody User user) {
        String checkCodeRedis = (String) redisTemplate.opsForValue().get("checkCode_" +user.getMobile());
        System.out.println("控制层 获取出的 缓存数据"+checkCodeRedis);
        if(checkCodeRedis==null||checkCodeRedis.length()==0){
            //isEmpty是 java lang 包下 处理string的函数
            //isEmpty  但是 checkCodeRedis会报 空指针异常。

            //类似 情况 判断 逻辑代码 如果写到 service 可以通过抛出异常，来处理错误结果
            //但在这写 可以方便 写return 且可直接给出 异常类型
           return new Result(false,StatusCode.ERROR,"请先获取手机验证码");

        }
        if(!checkCodeRedis.equals(code)){
            return new Result(false,StatusCode.ERROR,"请输入正确的验证码");
        }
        System.out.println("控制层 获取出的 缓存数据"+checkCodeRedis);
        userService.add(user);
        return new Result(true, StatusCode.OK, "注册成功");
    }





    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param user
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        userService.add(user);
        return new Result(true, StatusCode.OK, "增加成功");
    }

    /**
     * 修改
     *
     * @param user
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除
     *          必须有admin 角色才能删除
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        userService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

}
